package com.lang.dao.impl;

import com.lang.dao.ProductDao;
import com.lang.entity.Page;
import com.lang.entity.Product;
import com.lang.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.SQLException;
import java.util.List;

/*
 * @Date : 2024/3/13 9:43
 * @Created by Lang
 * @ProjectName : LclShop
 */
public class ProductDaoImpl implements ProductDao {
    private QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());

    @Override
    public List<Product> getProductByType(String tId) {
        String sql = "select * from product where t_id = ?";
        try {
            return runner.query(sql, new BeanListHandler<>(Product.class), tId);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public long getTotal(String tid) {
        String sql = "select count(*) from product where t_id = ?";
        try {
            return (long)runner.query(sql, new ScalarHandler(), tid);
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return 0;
    }

    @Override
    public List<Product> selectByPage(String tid, int startIndex, int pageSize) {
        String sql = "select * from product where t_id=? limit ?,?";
        try {
            return  runner.query(sql,new BeanListHandler<>(Product.class),tid,startIndex,pageSize);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Product getProductById(String pid) {
        String sql = "select * from product where p_id = ?";
        try {
            return runner.query(sql, new BeanHandler<>(Product.class), pid);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
